#include <iostream>
#include <cstring>
#include <vector>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>

const int MAX_EVENTS = 10;
const int PORT = 50051;

void setNonBlocking(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}

int createServerSocket() {
    int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == -1) {
        perror("Error creating server socket");
        exit(EXIT_FAILURE);
    }

    sockaddr_in serverAddr{};
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(PORT);

    if (bind(serverSocket, reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)) == -1) {
        perror("Error binding server socket");
        close(serverSocket);
        exit(EXIT_FAILURE);
    }

    if (listen(serverSocket, SOMAXCONN) == -1) {
        perror("Error listening on server socket");
        close(serverSocket);
        exit(EXIT_FAILURE);
    }

    return serverSocket;
}

int main() {
    int serverSocket = createServerSocket();

    int epollFd = epoll_create1(0);
    if (epollFd == -1) {
        perror("Error creating epoll file descriptor");
        close(serverSocket);
        exit(EXIT_FAILURE);
    }

    epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = serverSocket;

    if (epoll_ctl(epollFd, EPOLL_CTL_ADD, serverSocket, &event) == -1) {
        perror("Error adding server socket to epoll");
        close(epollFd);
        close(serverSocket);
        exit(EXIT_FAILURE);
    }

    std::vector<epoll_event> events(MAX_EVENTS);

    std::cout << "Echo Server is listening on port " << PORT << std::endl;

    while (true) {
        int readyFdCount = epoll_wait(epollFd, events.data(), MAX_EVENTS, -1);
        if (readyFdCount == -1) {
            perror("Error in epoll_wait");
            break;
        }

        for (int i = 0; i < readyFdCount; ++i) {
            if (events[i].data.fd == serverSocket) {
                // New connection
                sockaddr_in clientAddr{};
                socklen_t clientAddrLen = sizeof(clientAddr);

                int clientSocket = accept(serverSocket, reinterpret_cast<sockaddr*>(&clientAddr), &clientAddrLen);
                if (clientSocket == -1) {
                    perror("Error accepting connection");
                    continue;
                }

                setNonBlocking(clientSocket);

                std::cout << "New connection from " << inet_ntoa(clientAddr.sin_addr) << ":" << ntohs(clientAddr.sin_port) << std::endl;

                event.events = EPOLLIN | EPOLLOUT | EPOLLET;
                event.data.fd = clientSocket;

                if (epoll_ctl(epollFd, EPOLL_CTL_ADD, clientSocket, &event) == -1) {
                    perror("Error adding client socket to epoll");
                    close(clientSocket);
                }
            } else {
                // Handle data from a client
                int clientSocket = events[i].data.fd;

                char buffer[1024];
                ssize_t bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0);
                if (bytesRead <= 0) {
                    // Connection closed or error
                    std::cout << "Client disconnected" << std::endl;
                    epoll_ctl(epollFd, EPOLL_CTL_DEL, clientSocket, nullptr);
                    close(clientSocket);
                } else {
                    std::cout << "Recv Count: " << bytesRead << std::endl;
                    // Echo back the received data
                    send(clientSocket, buffer, bytesRead, 0);
                }
            }
        }
    }

    close(epollFd);
    close(serverSocket);

    return 0;
}
